<?php

namespace App\Http\Controllers;

use App\Libs\Xlsx\XlsWriter;
use App\Repositories\UploadRepository;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 爱企查
 * Class AqcController
 * @package App\Http\Controllers
 * create_at: 2025-08-30 08:22:52
 * update_at: 2025-08-30 08:22:52
 */
class AqcController extends Controller
{
    public function import(Request $request)
    {
        ini_set('memory_limit', '1024M');
        set_time_limit(600);

        ob_end_flush();

        // 记录程序执行起始时间
        $execMicroTime = microtime(true);
        // 记录程序起始内存使用量
//        $memoryUsageStart = memory_get_usage();

        DB::transaction(function () use ($request) {

            // 字段读取类型
            $_importDataType = [];

            // 字段
            $fields = [
                "ent_name",
                "ent_status",
                "ent_legal_person",
                "reg_capital",
                "paid_in_capital",
                "establish_date",
                "approval_date",
                "business_term",
                "province",
                "city",
                "district",
                "tel",
                "more_tel",
                "email",
                "more_email",
                "unified_social_credit_code",
                "tax_identification_number",
                "registration_number",
                "organization_code",
                "insured_number",
                "ent_type",
                "industry",
                "ent_former_name",
                "registered_address",
                "latest_annual_report_address",
                "website",
                "business_scope",
                "created_at",
                "updated_at"
            ];

            // 文件上传
            $filePath = app(UploadRepository::class)->uploadFile($request, function ($fileObj) {
                $fileName = $fileObj->hashName();
                $filePath = "import/" . date("Ymd", time());

                return [$fileName, $filePath];
            });

            // 处理路径
            $path = mb_substr($filePath, strpos($filePath, "import/"));

            // 读取
            // 配置信息
            $conf = ['path' => str_replace('\\', '/', storage_path()) . '/app/public'];
            $cls = new XlsWriter($conf);

            try {
                // 读取测试文件
                $cls->openFile($path);
                $cls->openSheet();

                $i = 0;
                $data = [];
                $cur = date("Y-m-d H:i:s");
                while (($row = $cls->nextRow($_importDataType)) !== NULL) {
                    if (0 == $i) {
                        if (count($row) != count($fields) - 2) {
                            break;
                        }
                        // 第一行是标题
                        $i++;
                        continue;
                    }

                    if (isAllEmpty($row)) {
                        // 空行
                        break;
                    }

                    // trim
                    $row = array_map(function ($v) {
                        return trim($v);
                    }, $row);

                    $row[] = $cur;
                    $row[] = $cur;

                    $data[] = array_combine($fields, $row);

                    $i++;
                }

                // 导入数据
                $this->importMain($data);
            } catch (Exception $exception) {
                throw new Exception($exception->getMessage());
            } finally {
                // 手动销毁
                $cls->close();
                // 移除文件
                @unlink(storage_path('app/public') . '/' . $path);
            }
        });

        // 计算程序执行时间
        $elapsedTime = getElapsedTime($execMicroTime);
        // 计算程序执行内存
//        $size = memory_get_usage() - $memoryUsageStart;
//        $memoryUsage = $size < 0 ? 0 : $size;

//        return "导入完成， 执行时间 " . $elapsedTime . " s" . "， 内存使用量 " . getMemoryUsage($memoryUsage);
        return "导入完成， 执行时间：" . $elapsedTime . " s";
    }

    private function importMain($data)
    {
        if (empty($data)) {
            return true;
        }

//        $data = array_reverse($data);

        // 写入数据库
        $data = collect($data);
        $batchSize = 100;
        foreach ($data->chunk($batchSize) as $chunk) {
            DB::table('eps')->insert($chunk->all());
//            break;
        }

        return true;
    }
}
